/*
 * NaluJoiner.cpp
 *
 *  Created on: 2017年3月27日
 *      Author: chuanjiang.zh
 */

#include "NaluJoiner.h"
#include "H264PropParser.h"
#include "H265PropParser.h"
#include <stdio.h>
#include <iostream>

namespace av
{

NaluJoiner::NaluJoiner()
{
	m_buffer.ensure(1024 * 300);
}

NaluJoiner::~NaluJoiner()
{
}

bool NaluJoiner::write(const MPacket& inPkt, int naluType, MPacket& outPkt)
{
	bool success = false;
	if (isCompleteNalu(naluType))
	{
		ByteBuffer& buffer = m_buffer.getCurBuffer();
		if (buffer.empty())
		{
			outPkt = inPkt;
		}
		else
		{
			buffer.write(inPkt.data, inPkt.size);

			outPkt.type = inPkt.type;
			outPkt.data = buffer.data();
			outPkt.size = buffer.size();
			outPkt.pts = inPkt.pts;
			outPkt.duration = inPkt.duration;
			outPkt.flags = inPkt.flags;
		}

		success = true;

		m_buffer.switchBuffer().clear();
	}
	else
	{
		ByteBuffer& buffer = m_buffer.getCurBuffer();
		buffer.write(inPkt.data, inPkt.size);
	}
	return success;
}

bool NaluJoiner::isCompleteNalu(int naluType)
{
	return true;
}


bool H264NaluJoiner::isCompleteNalu(int naluType)
{
	if (naluType == NaluPacket::NALU_SEI)
	{
		return false;
	}
	else if (naluType == NaluPacket::NALU_SPS)
	{
		return false;
	}
	else if (naluType == NaluPacket::NALU_PPS)
	{
		return false;
	}
	return true;
}

bool H265NaluJoiner::isCompleteNalu(int naluType)
{
	if (naluType == NAL_UNIT_VPS)
	{
		return false;
	}
	else if (naluType == NAL_UNIT_SPS)
	{
		return false;
	}
	else if (naluType == NAL_UNIT_PPS)
	{
		return false;
	}
	else if (naluType == NAL_UNIT_PREFIX_SEI)
	{
		return false;
	}
	else if (naluType == NAL_UNIT_SUFFIX_SEI)
	{
		return false;
	}
	return true;
}


NaluJoiner* createNaluJoiner(int codecID)
{
	if (codecID == MCODEC_H264)
	{
		return new H264NaluJoiner();
	}
	else if (codecID == MCODEC_H265)
	{
		return new H265NaluJoiner();
	}
	return new NaluJoiner();
}


} /* namespace av */
